import { Router, Request, Response } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { getDatabase } from '../database/init'
import { recurringTaskScheduler } from '../services/recurringScheduler'
import { normalizeTimestamp } from '../utils/dateUtils'
import { authenticateToken } from '../middleware/auth'

const router = Router()

// 所有重复任务路由都需要认证
router.use(authenticateToken)

// 获取所有重复任务
router.get('/', async (req: Request, res: Response) => {
  try {
    const db = getDatabase()
    
    const result = await db.query(`
      SELECT rt.*, 
             COUNT(rti.id) as instance_count,
             COUNT(CASE WHEN t.completed = FALSE THEN 1 END) as pending_count
      FROM recurring_tasks rt
      LEFT JOIN recurring_task_instances rti ON rt.id = rti.recurring_task_id
      LEFT JOIN tasks t ON rti.task_id = t.id
      WHERE rt.user_id = $1
      GROUP BY rt.id
      ORDER BY rt.created_at DESC
    `, [req.userId])
    
    const recurringTasks = result.rows.map((row: any) => ({
      id: row.id,
      title: row.title,
      description: row.description,
      priority: row.priority,
      category: row.category,
      tags: row.tags,
      notes: row.notes,
      recurringType: row.recurring_type,
      recurringPattern: row.recurring_pattern,
      isActive: row.is_active,
      createdAt: row.created_at,
      updatedAt: row.updated_at,
      userId: row.user_id,
      instanceCount: parseInt(row.instance_count) || 0,
      pendingCount: parseInt(row.pending_count) || 0
    }))
    
    res.json(recurringTasks)
  } catch (error) {
    console.error('获取重复任务失败:', error)
    res.status(500).json({ error: '获取重复任务失败' })
  }
})

// 获取单个重复任务详情
router.get('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    const result = await db.query(`
      SELECT rt.*,
             json_agg(
               json_build_object(
                 'id', rti.id,
                 'taskId', rti.task_id,
                 'dueDate', rti.due_date,
                 'createdAt', rti.created_at,
                 'completed', t.completed,
                 'completedAt', t.updated_at
               ) ORDER BY t.completed ASC, rti.due_date ASC
             ) FILTER (WHERE rti.id IS NOT NULL) as instances
      FROM recurring_tasks rt
      LEFT JOIN recurring_task_instances rti ON rt.id = rti.recurring_task_id
      LEFT JOIN tasks t ON rti.task_id = t.id
      WHERE rt.id = $1 AND rt.user_id = $2
      GROUP BY rt.id
    `, [id, req.userId])
    
    if (result.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在' })
    }
    
    const row = result.rows[0]
    const recurringTask = {
      id: row.id,
      title: row.title,
      description: row.description,
      priority: row.priority,
      category: row.category,
      tags: row.tags,
      notes: row.notes,
      recurringType: row.recurring_type,
      recurringPattern: row.recurring_pattern,
      isActive: row.is_active,
      createdAt: row.created_at,
      updatedAt: row.updated_at,
      userId: row.user_id,
      instances: row.instances || []
    }
    
    res.json(recurringTask)
  } catch (error) {
    console.error('获取重复任务详情失败:', error)
    res.status(500).json({ error: '获取重复任务详情失败' })
  }
})

// 创建重复任务
router.post('/', async (req: Request, res: Response) => {
  try {
    const {
      title, description, priority, category, tags, notes,
      recurringType, recurringPattern
    } = req.body
    
    if (!title || !recurringType) {
      return res.status(400).json({ error: '任务标题和重复类型不能为空' })
    }
    
    const id = uuidv4()
    const now = normalizeTimestamp(new Date())
    
    const db = getDatabase()
    
    // 创建重复任务模板
    // 处理 recurringPattern - 确保是有效的 JSON 或 null
    let processedRecurringPattern = null
    if (recurringPattern) {
      try {
        // 如果是字符串，尝试解析为 JSON
        if (typeof recurringPattern === 'string') {
          processedRecurringPattern = recurringPattern.trim() ? JSON.parse(recurringPattern) : null
        } else {
          processedRecurringPattern = recurringPattern
        }
      } catch (error) {
        // 如果解析失败，将字符串作为简单对象存储
        processedRecurringPattern = { pattern: recurringPattern }
      }
    }
    
    await db.query(`
      INSERT INTO recurring_tasks (
        id, title, description, priority, category, tags, notes,
        recurring_type, recurring_pattern, is_active, user_id, created_at, updated_at
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
    `, [
      id, title, description, priority || 'P2', category || 'work',
      tags || [], notes, recurringType, processedRecurringPattern, true,
      req.userId, now, now
    ])
    
    // 立即生成初始任务实例
    try {
      await recurringTaskScheduler.generateInstancesForTask(id, req.userId)
    } catch (error) {
      console.error('生成初始任务实例失败:', error)
    }
    
    res.status(201).json({
      id,
      message: '重复任务创建成功'
    })
  } catch (error) {
    console.error('创建重复任务失败:', error)
    res.status(500).json({ error: '创建重复任务失败' })
  }
})

// 更新重复任务
router.put('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const {
      title, description, priority, category, tags, notes,
      recurringType, recurringPattern, isActive
    } = req.body
    
    if (!title) {
      return res.status(400).json({ error: '任务标题不能为空' })
    }
    
    const db = getDatabase()
    const now = normalizeTimestamp(new Date())
    
    const result = await db.query(`
      UPDATE recurring_tasks SET
        title = $1, description = $2, priority = $3, category = $4,
        tags = $5, notes = $6, recurring_type = $7, recurring_pattern = $8,
        is_active = $9, updated_at = $10
      WHERE id = $11 AND user_id = $12
      RETURNING *
    `, [
      title, description, priority, category, tags, notes,
      recurringType, recurringPattern, isActive, now, id, req.userId
    ])
    
    if (result.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在' })
    }
    
    // 如果重复任务被重新激活，生成新的实例
    if (isActive) {
      try {
        await recurringTaskScheduler.generateInstancesForTask(id, req.userId)
      } catch (error) {
        console.error('生成任务实例失败:', error)
      }
    }
    
    res.json({
      message: '重复任务更新成功',
      recurringTask: result.rows[0]
    })
  } catch (error) {
    console.error('更新重复任务失败:', error)
    res.status(500).json({ error: '更新重复任务失败' })
  }
})

// 暂停重复任务
router.patch('/:id/pause', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    // 验证任务所有权
    const taskCheck = await db.query('SELECT id FROM recurring_tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在或无权访问' })
    }
    
    await recurringTaskScheduler.pauseRecurringTask(id, req.userId)
    
    res.json({ message: '重复任务已暂停' })
  } catch (error) {
    console.error('暂停重复任务失败:', error)
    res.status(500).json({ error: '暂停重复任务失败' })
  }
})

// 恢复重复任务
router.patch('/:id/resume', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    // 验证任务所有权
    const taskCheck = await db.query('SELECT id FROM recurring_tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在或无权访问' })
    }
    
    await recurringTaskScheduler.resumeRecurringTask(id, req.userId)
    
    // 恢复后立即生成实例
    await recurringTaskScheduler.generateInstancesForTask(id)
    
    res.json({ message: '重复任务已恢复' })
  } catch (error) {
    console.error('恢复重复任务失败:', error)
    res.status(500).json({ error: '恢复重复任务失败' })
  }
})

// 获取重复任务的所有实例
router.get('/:id/instances', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    // 首先验证重复任务是否属于当前用户
    const taskCheck = await db.query('SELECT id FROM recurring_tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在或无权访问' })
    }
    
    const result = await db.query(`
      SELECT t.*, rti.due_date as original_due_date, rti.created_at as instance_created_at
      FROM recurring_task_instances rti
      JOIN tasks t ON rti.task_id = t.id
      WHERE rti.recurring_task_id = $1 AND t.user_id = $2
      ORDER BY t.completed ASC, rti.due_date ASC
    `, [id, req.userId])
    
    const instances = result.rows.map((row: any) => ({
      id: row.id,
      title: row.title,
      description: row.description,
      dueDate: row.due_date,
      priority: row.priority,
      category: row.category,
      tags: row.tags,
      status: row.status,
      completed: row.completed,
      completedAt: row.completed_at,
      createdAt: row.created_at,
      updatedAt: row.updated_at,
      recurringTaskId: id,
      originalDueDate: row.original_due_date,
      instanceCreatedAt: row.instance_created_at
    }))
    
    res.json(instances)
  } catch (error) {
    console.error('获取重复任务实例失败:', error)
    res.status(500).json({ error: '获取重复任务实例失败' })
  }
})

// 手动生成任务实例
router.post('/:id/generate', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    // 验证任务所有权
    const taskCheck = await db.query('SELECT id FROM recurring_tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在或无权访问' })
    }
    
    const taskIds = await recurringTaskScheduler.generateInstancesForTask(id, req.userId)
    
    res.json({
      message: '任务实例生成成功',
      generatedTaskIds: taskIds,
      count: taskIds.length
    })
  } catch (error) {
    console.error('生成任务实例失败:', error)
    res.status(500).json({ error: '生成任务实例失败' })
  }
})

// 删除重复任务
router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    // 验证任务所有权
    const taskCheck = await db.query('SELECT id FROM recurring_tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '重复任务不存在或无权访问' })
    }
    
    await recurringTaskScheduler.deleteRecurringTask(id, req.userId)
    
    res.json({ message: '重复任务删除成功' })
  } catch (error) {
    console.error('删除重复任务失败:', error)
    res.status(500).json({ error: '删除重复任务失败' })
  }
})

// 获取重复任务统计
router.get('/stats/overview', async (req: Request, res: Response) => {
  try {
    if (!req.userId) {
      return res.status(401).json({ error: '用户未认证' })
    }
    const stats = await recurringTaskScheduler.getRecurringTaskStats(req.userId)
    res.json(stats)
  } catch (error) {
    console.error('获取重复任务统计失败:', error)
    res.status(500).json({ error: '获取重复任务统计失败' })
  }
})

// 手动触发重复任务处理
router.post('/trigger-processing', async (req: Request, res: Response) => {
  try {
    await recurringTaskScheduler.triggerProcessing()
    res.json({ message: '重复任务处理已触发' })
  } catch (error) {
    console.error('触发重复任务处理失败:', error)
    res.status(500).json({ error: '触发重复任务处理失败' })
  }
})

// 清理过期实例记录
router.post('/cleanup', async (req: Request, res: Response) => {
  try {
    const { daysToKeep = 30 } = req.body
    
    await recurringTaskScheduler.cleanupOldInstances(daysToKeep)
    
    res.json({ message: '过期实例清理完成' })
  } catch (error) {
    console.error('清理过期实例失败:', error)
    res.status(500).json({ error: '清理过期实例失败' })
  }
})

export { router as recurringRoutes }
